package com.dminvoicemanager;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONStringer;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class DM_Meter_Reading extends Activity {

	private String DBNAME = "dminvoicemanager.db";
	// Master Tables
	private String USER_SETTINGS = "usersettings";
	private String ITEM_AREA = "fArea";
	private String ITEM_COMPANY_SETTING = "fCompanySetting";
	private String ITEM_CONTROL = "fMeterRead";
	private String METER_READING_HEAD = "fMeterRead";
	private String ITEM_LOC_DETAILS = "fItemLoc";
	private String ITEM_LOCATION = "fLocation";
	private String ITEM_PRICE = "fItemPri";
	private String ITEMS = "fItems";
	private String INV_COMPANY_BRANCH = "FCompanyBranch";
	private String INV_SAL_REP = "fSalRep";

	// Stock Loading
	private String TEMP_STOCK_LOADING_SUMMARY = "frepStockLoadingSummary";
	private String STOCK_LOAD_HEAD = "fLoadhed";
	private String STOCK_LOAD_DETAIL = "fLoadDet";

	private SQLiteDatabase mydb;
	int count = 0;
	InputStream is = null;
	InputStream isp = null;
	StringBuilder sb = null;
	
	ProgressDialog mProgressDialog;
	AlertDialog StockLoadingAlert = null;
	final private static int DIALOG_SAVE_STOCK_LOADING = 1;
	final private static int DIALOG_SAVE_STOCK_LOADING_START = 2;
	final private static int DIALOG_UNDO_STOCK_LOADING = 3;
	final private static int DIALOG_PRINT_STOCK_LOADING = 4;
	private static final String TAG = null;


	EditText etdmstloadingdate,etdmstartRD,etdmsEndRD,etdmPrevoiusRd;
	Button btEnd,btBack,btStart;
	
	int startVal,EndVal,PreVal,LocationItemLoadRecId;

	// Mainclass
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_meter_reading);

		etdmstloadingdate = (EditText) findViewById(R.id.etdmstdate);
		etdmstloadingdate.setText(getCurrentTimeString());
		etdmPrevoiusRd = (EditText) findViewById(R.id.edtPreviousRd);
		btEnd = (Button) findViewById(R.id.Endbutton);
		btStart = (Button) findViewById(R.id.startbutton);
		
		etdmstartRD = (EditText) findViewById(R.id.etdmstarting);
		etdmsEndRD = (EditText) findViewById(R.id.edtendReading);
		btBack = (Button) findViewById(R.id.BtnBackAll);
		
		etdmPrevoiusRd.setEnabled(false);
		
			ISDBEmpty();
		
			if(ValidateDate() == false){
					
			LoadPrevoiousReading();
				
			}
			else {LoadPrevoiousReadingNtDate();}
		
		
		btEnd.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
	
				ValidateEndReading();
				
			}

		});
		
		btStart.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
	
				ValidateStartReading();
				
			}

		});
		
		
		btBack.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_InvoiceMenu.class);
				myIntent.putExtra("TAGID", "5");
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();

			}

		});
	
	}
	
	
	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			// Check Current Agent Prefix
	

			private void ValidateEndReading() {
				// TODO Auto-generated method stub
				if(etdmsEndRD.length() == 0){
					
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_Meter_Reading.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("Validating End Reading");
				// Setting Dialog Message
				alertDialog.setMessage("End Reading Cannot Be Empty...");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								etdmsEndRD.setText("00"); 
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;
			}
				
				
				startVal = Integer
						.parseInt(etdmstartRD.getText().toString());
				EndVal =  Integer
						.parseInt(etdmsEndRD.getText().toString());
				
				Log.v("", "Length / Empty -:" + etdmsEndRD.getText().toString().length() + ":"+ etdmsEndRD.getText().toString().length());
				
				
				 if(startVal >= EndVal)
				{
					
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_Meter_Reading.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("Validating End Reading");
				// Setting Dialog Message
				alertDialog.setMessage("End Reading Cannot Be Less Than Start Reading...");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								etdmsEndRD.setText("000"); 
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;
			}

				else
			{
				etdmsEndRD.setEnabled(false);
				
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
				try{

					updateMeterRead();
				}
				catch (Exception e) {
					Toast.makeText(getApplicationContext(),
							"Error Occured..", Toast.LENGTH_SHORT)
							.show();
				}
				
			}
		}
			// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			
			//Update Meter Read Values
			
			private void updateMeterRead() {
				// TODO Auto-generated method stub
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
				Cursor checkUpdateAdjustSummary = null;
				Cursor checkLoadinghead = null;
				try {
					checkUpdateAdjustSummary = mydb.query(METER_READING_HEAD,
							null, "txndate= '"+ etdmstloadingdate.getText().toString() +"' AND PreviRd='"
									+ etdmPrevoiusRd.getText().toString() + "'",
							null, null, null, null);
					
					checkLoadinghead = mydb.query(STOCK_LOAD_HEAD,
							null, "txndate= '"+ etdmstloadingdate.getText().toString() + "'",
							null, null, null, null);
					
					
				} catch (Exception e) {
				}
//				if (checkLoadinghead != null) {
//					if (checkLoadinghead.getCount() > 0) {
						
				
				if (checkUpdateAdjustSummary != null) {
					if (checkUpdateAdjustSummary.getCount() > 0) {
						while (checkUpdateAdjustSummary.moveToNext()) {
							String adjsumrecid = checkUpdateAdjustSummary.getString(0);
							ContentValues newStockLoadRecDetailP = new ContentValues();
						    newStockLoadRecDetailP.put("TxnDate", etdmstloadingdate
									.getText().toString());
							newStockLoadRecDetailP.put("StartRd",etdmstartRD.getText().toString());
							newStockLoadRecDetailP.put("EndRd", etdmsEndRD.getText().toString());
							newStockLoadRecDetailP.put("PreviRd", etdmPrevoiusRd.getText().toString());
							newStockLoadRecDetailP.put("stldmhedSync", "2");

							mydb.update(METER_READING_HEAD,
									newStockLoadRecDetailP, "RecordId ='"
											+ adjsumrecid + "'", null);
							
							final AlertDialog alertDialog = new AlertDialog.Builder(
									DM_Meter_Reading.this).create();
							// Setting Dialog Title
							alertDialog.setTitle("UPDATE");
							// Setting Dialog Message
							alertDialog.setMessage("End Record Insert Successfully");
							// Setting Icon to Dialog
							alertDialog.setIcon(R.drawable.warning);
							// Setting OK Button
							alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									alertDialog.dismiss();
								
								}
							});
							// Showing Alert Message
							alertDialog.show();
							alertDialog.setCanceledOnTouchOutside(false);
							
							
							
//									try {
//										showDialog(DIALOG_SAVE_STOCK_LOADING);
//									} catch (Exception ex) {
//										ex.printStackTrace();
//									}
//							
								}
							}
						}
				
				
//					}else{
//						
//						final AlertDialog alertDialog = new AlertDialog.Builder(
//								DM_Meter_Reading.this).create();
//						// Setting Dialog Title
//						alertDialog.setTitle("Validating End Reading");
//						// Setting Dialog Message
//						alertDialog.setMessage("Stock Loading Empty..Cannot Enter End Reading...");
//						// Setting Icon to Dialog
//						alertDialog.setIcon(R.drawable.warning);
//						// Setting OK Button
//						alertDialog.setButton("OK",
//								new DialogInterface.OnClickListener() {
//									public void onClick(DialogInterface dialog,
//											int which) {
//										etdmsEndRD.setText("");
//										etdmsEndRD.setEnabled(true);
//										alertDialog.dismiss();
//									}
//								});
//						// Showing Alert Message
//						alertDialog.show();
//						alertDialog.setCanceledOnTouchOutside(false);
//						return;
//						
//					}
							
				}

	//		}

			
			//--------------Load Values If Date equals To Current Date--------------//
			
			private void LoadPrevoiousReading(){
				
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
				Cursor selectAllMeterRead = null;

				try {
					selectAllMeterRead = mydb.query(METER_READING_HEAD, null, null, null,
							null, null, null);
					Log.v("", "Count / Update -:" + selectAllMeterRead.getCount() + ":"+ selectAllMeterRead.getCount());
				} catch (Exception e) {
				}
				if (selectAllMeterRead != null) {
					if (selectAllMeterRead.getCount() > 0) {
						while (selectAllMeterRead.moveToNext()) {
							
							String PreRd = selectAllMeterRead.getString(4);
							etdmPrevoiusRd.setText(PreRd.toString());
							String StrRd = selectAllMeterRead.getString(2);
							etdmstartRD.setText(StrRd.toString());
							String stldmhedSync = selectAllMeterRead.getString(5);
							String StrEnd = selectAllMeterRead.getString(3);
							etdmstartRD.setEnabled(false);
							btStart.setEnabled(false);
								if(stldmhedSync.toString().trim().equalsIgnoreCase("2")){
									etdmsEndRD.setText(StrEnd.toString());
								}
								if(PreRd.equals(StrEnd))
								{
									etdmsEndRD.setText("00");
								}
						}

					}else{
						etdmPrevoiusRd.setText("0");
						etdmstartRD.setText("00");
						etdmsEndRD.setEnabled(false);
						btEnd.setEnabled(false);						
					}
				}
				
				selectAllMeterRead.close();
				mydb.close();

			}
			
			//-------------------------------------------------------------------//
			
			//--------------------Load Values If Date Not Equals To Current Date---------------------//
			
				private void LoadPrevoiousReadingNtDate(){
				
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
				Cursor selectAllMeterRead = null;

				try {
					selectAllMeterRead = mydb.query(METER_READING_HEAD, null, null, null,
							null, null, null);
					Log.v("", "Count / Update -:" + selectAllMeterRead.getCount() + ":"+ selectAllMeterRead.getCount());
				} catch (Exception e) {
				}
				if (selectAllMeterRead != null) {
					if (selectAllMeterRead.getCount() > 0) {
						while (selectAllMeterRead.moveToNext()) {
							
							String PreRd = selectAllMeterRead.getString(3);
							etdmPrevoiusRd.setText(PreRd.toString());
							etdmsEndRD.setText("00");
							etdmstartRD.setText("00");
							etdmsEndRD.setEnabled(false);
							btEnd.setEnabled(false);
						}

					}else{
						etdmPrevoiusRd.setText("00");
						etdmstartRD.setText("00");
						etdmsEndRD.setEnabled(false);
						btEnd.setEnabled(false);
					
					}
				}
				
				selectAllMeterRead.close();
				mydb.close();
				

			}
			
		//---------------------------------------------------------------------------------//
				
				
			
			private void ValidateStartReading(){
				
				startVal = Integer
						.parseInt(etdmstartRD.getText().toString());
				PreVal =  Integer
						.parseInt(etdmPrevoiusRd.getText().toString());
				
				
				if(PreVal >= startVal)
				{
					
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_Meter_Reading.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("Validating Start Reading");
				// Setting Dialog Message
				alertDialog.setMessage("Start Reading Cannot Be Less Than Prevoius Reading...");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								etdmstartRD.setText("000"); 
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;
			} else if(etdmstartRD.getText().toString()== ""){
				
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_Meter_Reading.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("Validating Start Reading");
				// Setting Dialog Message
				alertDialog.setMessage("Start Reading Cannot Be Empty...");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								etdmstartRD.setText("0"); 
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;
				
			}
				else
			{
				//Loack All the Transactions
				etdmstartRD.setEnabled(false);
				etdmsEndRD.setEnabled(true);
				btEnd.setEnabled(true);
				etdmsEndRD.setText("00");
				btStart.setEnabled(false);
				
				if(ValidateDate()==true){
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
				
					
				try{
					ContentValues newStockLoadRecDetail = new ContentValues();
				    newStockLoadRecDetail.put("TxnDate", etdmstloadingdate
							.getText().toString());
					newStockLoadRecDetail.put("StartRd",etdmstartRD.getText().toString());
					newStockLoadRecDetail.put("EndRd", etdmPrevoiusRd.getText().toString());
					newStockLoadRecDetail.put("PreviRd", etdmPrevoiusRd.getText().toString());
					newStockLoadRecDetail.put("stldmhedSync", "0");
					mydb.insert(METER_READING_HEAD, null, newStockLoadRecDetail);
					
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_Meter_Reading.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("INSERT");
					// Setting Dialog Message
					alertDialog.setMessage("Start Record Insert Successfully");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							alertDialog.dismiss();
						
						}
					});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
				}
				catch (Exception e) {
					Toast.makeText(getApplicationContext(),
							"Error Occured..", Toast.LENGTH_SHORT)
							.show();
				}
				mydb.close();
				}
				
			  }
				
			}
			
			
			//-------------Validate Meter For Current Date----------//
			private Boolean ValidateDate() {
				
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
				Cursor selectAllMeterRead = null;
				Boolean val = false;
				try {
					selectAllMeterRead = mydb.query(METER_READING_HEAD, null, null,
							null, null, null, null);
					Log.v("", "Count / Update -:" + selectAllMeterRead.getCount() + ":"+ selectAllMeterRead.getCount());
				} catch (Exception e) {
				}
				if (selectAllMeterRead != null) {
					if (selectAllMeterRead.getCount() > 0) {
						while (selectAllMeterRead.moveToNext()) {
							
							String DateTxn = selectAllMeterRead.getString(1);
							String DateEtext = etdmstloadingdate.getText().toString();
							
							if(DateTxn.equalsIgnoreCase(DateEtext)){
							
							val = false;
							
							//update to meter table
							}
							else{
								etdmstartRD.setEnabled(true);
								etdmsEndRD.setEnabled(true);
								val = true;
								//insert to meter table
							}
						}
						
					}else{
						//etdmstartRD.setText("00");
						val = true;
					}
					
				}
				
				
				selectAllMeterRead.close();
				mydb.close();
				return val;
			}
			
			private void ISDBEmpty(){
				
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
				Cursor selectAllMeterRead = null;
				
				try {
					selectAllMeterRead = mydb.query(METER_READING_HEAD, null, null,
							null, null, null, null);
					Log.v("", "Count / Update -:" + selectAllMeterRead.getCount() + ":"+ selectAllMeterRead.getCount());
				} catch (Exception e) {
				}
				if (selectAllMeterRead != null) {
					if (selectAllMeterRead.getCount() == 0) {
						
						etdmPrevoiusRd.setText("00");
						etdmsEndRD.setEnabled(false);
						btEnd.setEnabled(false);
						etdmsEndRD.setText("0000");
						etdmstartRD.setText("0000");
					}
					
				}
				
				
				selectAllMeterRead.close();
				mydb.close();
				//return val;
				
			}
	

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// get current data and time
	private String getCurrentTimeStringCustom() {
		Calendar c = Calendar.getInstance();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String formattedDate = df.format(c.getTime());
		return formattedDate;
	}

	private String getCurrentTimeString() {
		// 2013-10-04 00:00:00.000
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("dd/MM/yyyy");
		String date_to_string = ddMMMyyFormat.format(dateNow);
		return date_to_string;
	}
	
	// Handling Dialog Box Functions
		@Override
		protected Dialog onCreateDialog(int id) {
			switch (id) {
			case DIALOG_SAVE_STOCK_LOADING:
				LayoutInflater inflater = LayoutInflater.from(this);
				View dialogview = inflater.inflate(
						R.layout.dm_dialog_save_adjustment, null);

				AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
				dialogbuilder.setTitle("Save End Meter Reading Successfully");
				dialogbuilder.setView(dialogview);
				StockLoadingAlert = dialogbuilder.create();
				StockLoadingAlert.setCanceledOnTouchOutside(false);
				break;
				
			case DIALOG_SAVE_STOCK_LOADING_START:
				LayoutInflater inflaterstl = LayoutInflater.from(this);
				View dialogviewstl = inflaterstl.inflate(
						R.layout.dm_dialog_save_adjustment, null);

				AlertDialog.Builder dialogbuilderstl = new AlertDialog.Builder(this);
				dialogbuilderstl.setTitle("Save Start Meter Reading Successfully...");
				dialogbuilderstl.setView(dialogviewstl);
				StockLoadingAlert = dialogbuilderstl.create();
				StockLoadingAlert.setCanceledOnTouchOutside(false);
				break;

			}

			return StockLoadingAlert;

		}

		
		public void btnBack(View view) {
			Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			myIntent.putExtra("TAGID", "SALES");
			startActivityForResult(myIntent, 0);
			finish();
		}
		

	

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}

}
